import React, { useState } from 'react';
import s from './style.module.css';
import i from '../../../common.module.css';
import {
  Table,
  Pagination,
  Textarea,
  Input,
  Confirm,
  Button,
  Message,
  Form,
  Loading,
  Dialog
} from '@knownsec/react-component';
import { Whitekey, whitekeyAdd, whitekeyDel } from '~/API';
import cn from 'classnames';

const defaultSearch = {
  word: '',
  page: 1,
  count: 10,
};
export default function keyword() {
  const [refe, setRef] = useState(false);
  const [loading, setLoading] = useState(true);
  const [selTable, setSelTable] = useState([]);
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [searchInfo, setSearchInfo] = useState(defaultSearch);
  const createForm = React.useRef();
  const columns = [
    {
      title: '敏感词',
      dataIndex: 'word',
      // className: s.w_5,?
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.w_5,
      render: (e, row) => {
        const id = row._id;
        return (
          <div
            className={s.operation}
            onClick={() => {
              delList([id]);
            }}
          >
            删除
          </div>
        );
      },
    },
  ];
  const getList = async (e) => {
    setSelTable([])
    setRef(!refe)
    const res = await Whitekey(e);
    const data = res.data.results.data.map((e) => {
      e.id = e._id;
      return e;
    });
    setTableData({ data, total: res.data.results.count });
    setLoading(false);
  };
  const onSearch = (e) => {
    let params = { page: 1, count: 10 };
    if (e.page) {
      setSearchInfo({ ...searchInfo, page: e.page, count: e.limit });
      params = { ...searchInfo, page: e.page, count: e.limit };
    } else {
      params = { ...params, word: e.word };
    }
    getList(params);
  };
  React.useMemo(() => {
    getList({ page: 1, count: 10 });
  }, []);
  function validatormap(rule, value, callback) {
    const length = value.split(' ').every((e) => {
      return e.length <= 40;
    });
    if (!length) {
      callback('*敏感词超长');
    }
  }
  const [visible, setVisible] = useState(false)
  const [keyword, setKeyword] = useState('')
  const onsubmit = async () => {
    const res = await whitekeyAdd({ white_keywords: keyword });
    if (res.status === 'success') {
      Message.show({
        pro: true,
        showClose: false,
        type: 'success',
        message: '添加成功',
      });
    }
    setVisible(false)
    createForm.current.resetFields()
    setKeyword('');
    getList({ page: 1, count: 10 });
  }
  const delList = (e) => {
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">确认要删除吗？</div>,
      onconfirm: async () => {
        const params = {
          whitekey_ids: e || selTable,
        };
        const res = await whitekeyDel(params);
        getList({ page: 1, count: 10 });
        if (res.data.code === 0) {
          setSelTable([]);
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message: '删除成功',
          });
        }
      },
      oncancel: () => {},
    });
  };
  return (
    <div className={s.wordMain}>
      <div className={s.tool}>
        <div className={s.btnBox}>
          <Button
            pro
            type="primary"
            onClick={() => {
              setVisible(true);
              setKeyword('');
            }}
          >
            添加
          </Button>
        </div>
        <Input
          pro
          value={searchInfo.word}
          search
          clear
          autoComplete={'off'}
          onSearch={(e) => {
            onSearch({ word: e.value });
          }}
          className={cn('search-button', s.mr0)}
          placeholder="请输入敏感词"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, word: e.value });
            e.value === '' && onSearch({ word: e.value });
          }}
        />
      </div>
      <div>
      <Button
        pro
        type="text"
        className="delete-btn p0"
        onClick={() => {
          delList();
        }}
        disabled={!selTable.length}
      >
        批量删除
      </Button>
      </div>
      <Table
        refre={refe}
        selectable
        columns={columns}
        tableLoading={loading}
        loadingLabel=""
        className={cn(s.table, selTable[0] ? 'half-select' : '')}
        data={tableData.data}
        getCheckedList={(e) => {
          setSelTable(e);
        }}
      ></Table>
      {tableData.total > 10 && <Pagination
        key={Number(123)}
        className={s.pagination}
        current={searchInfo.page}
        showQuickJumper={{ goButton: true }}
        showSizeChanger={true}
        pageSize={searchInfo.count}
        pageSizeOptions={['10', '20', '50']}
        total={tableData.total}
        showTotal={(total) => `共${total}条`}
        onChange={(page, limit) => {
          onSearch({ page, limit });
        }}
      />}
      <Dialog 
        className="w540" 
        title="白名单词设置" 
        visible={visible} 
        cusCancel={<Button type="default" className={i.mr20} onClick={() => {
          setVisible(false)
          setKeyword('');
          createForm.current.resetFields()
        }}>取消</Button>}
        onhide={() => {
          setVisible(false);
          createForm.current.resetFields()
          setKeyword('');
        }} onsubmit={onsubmit}>
        <div className={s.p24}>
          <Form
            ref={createForm}
            onValuesChange={(newItem) => {
              setKeyword(newItem.cust_keywords);
            }}
          >
            <Form.Item 
              className={s.mb0} 
              label="敏感词" 
              rules={[{ validator: validatormap }]} 
              name="cust_keywords">
              <Textarea
                rows='6'
                className={cn(s.textArea, s.text)}
                placeholder="请输入敏感词，按空格隔开，每个敏感词不超过40字符。"
              ></Textarea>
            </Form.Item>
          </Form>
        </div>
      </Dialog>
    </div>
  );
}
